package com.basis.handler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.hibernate.Query;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.SessionInfo;
import org.openbravo.model.ad.access.User;

@SuppressWarnings("unchecked")
public class MessageAlertHandler extends BaseActionHandler {
	private Logger logger = Logger.getLogger(this.getClass());
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	@Override
	protected JSONObject execute(Map<String, Object> parameters, String data) {
		JSONObject result = new JSONObject();
		try {
			OBContext.setAdminMode();
			User user = OBDal.getInstance().get(User.class, SessionInfo.getUserId());
			String sql = "select m.title, m.text, m.url, m.Emes_Message_id, m.created " +
				         "  from Emes_Message m, Emes_Message_User_Log ul" +
				         " where m.emes_message_id = ul.emes_message_id" +
				         "   and ul.send_mode = 'WINDOW'" +
				         "   and m.created >= trunc(now()) - 3" +//查询最近3天的数据，之前数据过滤掉
				         "   and nvl(ul.status, 'CREATE') = 'CREATE'" +
				         "   and ul.ad_user_id = ?" +
				         " order by m.created desc";
			Query query = OBDal.getInstance().getSession().createSQLQuery(sql);
			query.setString(0, user.getId());
			
			query.setFetchSize(10);
			query.setFirstResult(0);
			List<Object[]> list = query.list();
			
			JSONArray array = new JSONArray();
			JSONObject row = null;
			
			for (Object[] arr : list) {
				row = new JSONObject();
				row.put("title", arr[0]);
				row.put("text", arr[1]);
				row.put("url", arr[2]);
				row.put("id", arr[3]);
				row.put("date", dateFormat.format((Date)arr[4]));
				
				array.put(row);
			}
			OBDal.getInstance().commitAndClose();
			result.put("list", array);
			result.put("success", true);
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			logger.error("获取消息提醒内容异常：" + e.getMessage(), e);
			try {
				result.put("success", false);
				result.put("msg", "查询用户消息提醒内容异常");
			} catch (Exception e1) {
			}
		} finally {
			OBContext.restorePreviousMode();
		}
		return result;
	}
}